"use client";
import { useEffect, useRef } from "react";
import { Terminal } from "@xterm/xterm";
import { FitAddon } from "@xterm/addon-fit";
import "@xterm/xterm/css/xterm.css";
import figlet from "figlet";
// @ts-expect-error: No type definitions for figlet/importable-fonts/Standard.js
import standard from "figlet/importable-fonts/Standard.js";
import colors from "ansi-colors-browserify";

export function GameTerminal() {
  const terminalRef = useRef<HTMLDivElement>(null);
  const terminalInstance = useRef<Terminal | null>(null);
  const fitAddon = useRef(new FitAddon());

  useEffect(() => {
    if (!terminalRef.current) return;

    // 1. Initialize terminal
    terminalInstance.current = new Terminal({
      theme: {
        background: "hsl(var(--background))",
        foreground: "hsl(var(--foreground))"
      },
      fontFamily: "'Fira Code', Menlo, monospace",
      fontSize: 16,
      allowProposedApi: true,
      scrollback: 1000,
      convertEol: true
    });

    if (!terminalInstance.current) return;

    // 2. Load essential addons
    terminalInstance.current.loadAddon(fitAddon.current);

    // 3. Open terminal AFTER DOM is ready
    terminalInstance.current.open(terminalRef.current);

    // 4. Force resize calculation
    setTimeout(() => {
      fitAddon.current.fit();
      terminalInstance.current?.focus();
    }, 10);

    // Initial ASCII art
    figlet.parseFont("Standard", standard);
    figlet.text(
      "Dungeon RPG",
      {
        font: "Standard"
      },
      (_, art) => {
        if (art && terminalInstance.current) {
          terminalInstance.current.writeln("");
          terminalInstance.current.writeln(colors.magenta.bold(art));
          terminalInstance.current.writeln("");
          terminalInstance.current.writeln(colors.green("Welcome to the dungeon!"));
          terminalInstance.current.writeln("");
          terminalInstance.current.write("> ");
        }
      }
    );

    // Input handling
    terminalInstance.current.onData(data => {
      // Handle commands here
      console.log(data);
    });

    return () => {
      terminalInstance.current?.dispose();
    };
  }, []);

  return <div ref={terminalRef} className="h-[600px] w-full rounded-lg border"></div>;
}
